"""
:Author: Sven Walter <sven.walter@wltr.eu>
:Since: 11.03.2011
"""

import pickle


from django.db import models
from django.core.exceptions import ValidationError


class ObjectField( models.Field ):
    description = "Kann ein beliebiges Python-Objekt speichern."
    
    __metaclass__ = models.SubfieldBase
    
    def __init__(self, *args, **kwargs):
        self.type = kwargs.pop('type',None)
        kwargs.setdefault('editable', False)
        super(ObjectField, self).__init__(*args, **kwargs)

    def db_type(self, connection): #@UnusedVariable
        return 'longblob'

    def to_python(self,value):
        if not value:
            return None
        
        if isinstance(value, (str,unicode)):
            object = pickle.loads( value )
        else:
            object = value
            
        if not self.type:
            return object
        
        type_ns = type(object).__module__+"."+type(object).__name__
        if ((isinstance(self.type, str) and type_ns != self.type) or
            not isinstance(object, self.type)):
            raise ValidationError( u"Instanz muss vom Typ '{0}' sein.".format(self.type) )
        
        return object

    def get_prep_value(self, value):
        if isinstance(value, (str,unicode)):
            return value
        return pickle.dumps(value)